package com.github.edu.repair.web.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.admin.edu.assembly.common.entity.JsonArray;
import com.github.admin.edu.assembly.common.entity.JsonEntity;
import com.github.admin.edu.assembly.common.util.JsonUtils;
import com.github.admin.edu.assembly.date.util.DateFormatUtils;
import com.github.admin.edu.assembly.page.entity.Pager;
import com.github.admin.edu.assembly.string.util.StringUtils;
import com.github.admin.edu.oauth.server.api.entity.TSysUser;
import com.github.admin.edu.oauth.server.api.entity.TUserInformation;
import com.github.edu.repair.api.entity.*;
import com.github.edu.repair.web.domain.*;
import com.github.edu.repair.web.service.UserRepairService;
import com.github.edu.security.login.domain.UserLoginDomain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-8-23
 */
@Slf4j
@Service
public class UserRepairServiceImpl implements UserRepairService {

    @Autowired
    private UserRepairDomain domain;

    @Autowired
    private UserLoginDomain loginDomain;

    @Autowired
    private FwdlManagerDomain fwdlManagerDomain;

    @Autowired
    private FwflManagerDomain fwflManagerDomain;

    @Autowired
    private LyqyManagerDomain lyqyManagerDomain;

    @Autowired
    private LyxxManagerDomain lyxxManagerDomain;

    /**
     * 用户开始申请
     *
     * @param map
     * @param userId
     */
    @Override
    public void userRepair(ModelMap map, String userId) {
        TSysUser tSysUser = getUserInformation(userId);
        TBxBxsq tBxBxsq = new TBxBxsq();
        try {
            tBxBxsq.setLcbh(DateFormatUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS"));
            tBxBxsq.setBxsj(DateFormatUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        map.put("user", tSysUser);
        map.put("entity", tBxBxsq);
        map.put("lyqyList", getAllLyxx());
        map.put("fwdlList", getAllFwdl());
    }

    /**
     * 获取用户基本信息
     *
     * @return
     */
    private TSysUser getUserInformation(String userId) {
        TSysUser sysUser = null;
        String code = loginDomain.getSysEntity(userId);
        if (StringUtils.isNotBlank(code)) {
            JsonEntity<TSysUser> jsonEntity = JsonUtils.toCollection(code,
                    new TypeReference<JsonEntity<TSysUser>>() {
                    });
            if (null != jsonEntity) {
                sysUser = jsonEntity.getData();
            }
        }
        return sysUser;
    }

    private TSysUser getUserInformationById(String id) {
        TSysUser sysUser = null;
        String code = loginDomain.getSysUser(id);
        if (StringUtils.isNotBlank(code)) {
            JsonEntity<TSysUser> jsonEntity = JsonUtils.toCollection(code,
                    new TypeReference<JsonEntity<TSysUser>>() {
                    });
            if (null != jsonEntity) {
                sysUser = jsonEntity.getData();
            }
        }
        return sysUser;
    }

    /**
     * 服务分类
     *
     * @return
     */
    private List<TBxFwdl> getAllFwdl() {
        String code = fwdlManagerDomain.getAll();
        List<TBxFwdl> list = null;
        if (StringUtils.isNotBlank(code)) {
            JsonArray<TBxFwdl> jsonArray = JsonUtils.toCollection(code, new TypeReference<JsonArray<TBxFwdl>>() {
            });
            if (null != jsonArray) {
                list = jsonArray.getDataList();
            }
        }
        return list;
    }

    /**
     * 服务类型
     *
     * @param id
     * @return
     */
    public List<TBxFwfl> getAllFwfl(Integer id) {
        String code = fwflManagerDomain.getAll(id);
        List<TBxFwfl> list = null;
        if (StringUtils.isNotBlank(code)) {
            JsonArray<TBxFwfl> jsonArray = JsonUtils.toCollection(code, new TypeReference<JsonArray<TBxFwfl>>() {
            });
            if (null != jsonArray) {
                list = jsonArray.getDataList();
            }
        }
        return list;
    }

    @Autowired
    private GzmsInformationDomain gzmsInformationDomain;

    @Override
    public void getAllGzms(ModelMap map, TBxGzms gzms, Pager pager) {
        if (null == gzms) {
            gzms = new TBxGzms();
        }
        if (null == pager) {
            pager = new Pager();
            pager.setCurrent(1);
            pager.setRows(10);
        }
        JsonEntity<TBxGzms> jsonEntity = new JsonEntity<>();
        jsonEntity.setPager(pager);
        jsonEntity.setData(gzms);
        List<TBxGzms> list = null;
        String code = gzmsInformationDomain.getALLByPager(JsonUtils.toJson(jsonEntity));
        if (StringUtils.isNotBlank(code)) {
            JsonArray<TBxGzms> jsonArray = JsonUtils.toCollection(code, new TypeReference<JsonArray<TBxGzms>>() {
            });
            if (null != jsonArray) {
                list = jsonArray.getDataList();
                pager = jsonArray.getPager();
            }
        }
        map.put("dataList", list);
        map.put("pager", pager);
        map.put("entity", gzms);
    }

    @Override
    public String getAllJsonGzms(TBxGzms gzms) {
        if (null == gzms) {
            gzms = new TBxGzms();
        }
        Pager pager = new Pager();
        pager.setCurrent(1);
        pager.setRows(10);
        JsonEntity<TBxGzms> jsonEntity = new JsonEntity<>();
        jsonEntity.setPager(pager);
        jsonEntity.setData(gzms);
        return gzmsInformationDomain.getALLByPager(JsonUtils.toJson(jsonEntity));
    }


    @Autowired
    private BxsqManagerDomain bxsqManagerDomain;

    @Autowired
    private SysStepWfManagerDomain wfManagerDomain;

    /**
     * 保存报修申请(step 1)
     *
     * @param map
     * @param bxBxsq
     */
    @Override
    public void saveRepair(ModelMap map, TBxBxsq bxBxsq,Integer stepId) {
        TSysUser tSysUser = getUserInformationById(bxBxsq.getBxr());
        JsonEntity<TBxBxsq> jsonEntity = new JsonEntity<>();
        jsonEntity.setData(bxBxsq);
        String code = bxsqManagerDomain.saveOrUpdate(JsonUtils.toJson(jsonEntity));
        if (StringUtils.isNotBlank(code)) {
            JsonEntity<TBxBxsq> entity = JsonUtils.toCollection(code, new TypeReference<JsonEntity<TBxBxsq>>() {
            });
            bxBxsq = entity.getData();
        }
        if(null==stepId){
            //todo: 保存完成后，执行流程步骤第一步
            TSysWfStep sysWfStep = getDbStep(1, bxBxsq.getLcbh());
            if (null == sysWfStep) {
                sysWfStep = new TSysWfStep();
                sysWfStep.setKssj(bxBxsq.getBxsj());
                sysWfStep.setLcbh(bxBxsq.getLcbh());
                sysWfStep.setLcid(bxBxsq.getId());
                sysWfStep.setStep(1);
                sysWfStep.setSpr(tSysUser.getUserid());
                JsonEntity<TSysWfStep> stepJsonEntity = new JsonEntity<>();
                stepJsonEntity.setData(sysWfStep);
                wfManagerDomain.saveOrUpdate(JsonUtils.toJson(stepJsonEntity));
            }
        }
        map.put("stepId",1);
        List<TBxFwfl> listFwfl = null;
        if (StringUtils.isNotBlank(bxBxsq.getGznr())) {
            String code_gzms = gzmsInformationDomain.getAllByIds(bxBxsq.getGznr());
            if (StringUtils.isNotBlank(code_gzms)) {
                JsonArray<TBxGzms> jsonArray = JsonUtils.toCollection(code_gzms, new TypeReference<JsonArray<TBxGzms>>() {
                });
                if (null != jsonArray) {
                    List<TBxGzms> list = jsonArray.getDataList();
                    String info = "";
                    if (null != list && list.size() > 0) {
                        for (TBxGzms tBxGzms : list) {
                            if (StringUtils.isBlank(info)) {
                                info = tBxGzms.getFwsm();
                            } else {
                                info = info + ";" + tBxGzms.getFwsm();
                            }
                        }
                    }
                    bxBxsq.setFwdlmc(info);
                }
            }
        }
        if (null != bxBxsq.getFwdl()) {
            listFwfl = getAllFwfl(bxBxsq.getFwdl());
        }
        map.put("user", tSysUser);
        map.put("entity", bxBxsq);
        map.put("lyqyList", getAllLyxx());
        map.put("fwdlList", getAllFwdl());
        map.put("listFwfl", listFwfl);
        map.put("stepId",stepId);
    }

    @Autowired
    private ServiceQueryUserInformationDomain informationDomain;

    @Autowired
    private SysRoleStepInformationDomain stepInformationDomain;

    @Override
    public boolean saveStep(ModelMap map, Integer stepId, TBxBxsq bxBxsq, String userId) {
        if (null != bxBxsq && StringUtils.isNotBlank(bxBxsq.getLcbh())) {
            try {
                //todo:根据步骤Id,用户id查询用户是否具有权限，执行此步骤，
                //todo：同时校验该步骤是否已经完成
                //todo:校验通过后， 保存申请信息
                //todo:保存此步骤，跟新上一步骤的结束时间
                //第一步，执行提交,提交成功后，产生下一步待办信息并完成本步
                if (stepId == 1) {//如果为第一步，只要验证申请人和提交人为同一人
                    TSysWfStep step = getDbStep(stepId, bxBxsq.getLcbh());
                    if(null==step&&null==bxBxsq.getId()){//说明没有保存
                        step=new TSysWfStep();
                        step.setKssj(bxBxsq.getBxsj());
                        step.setLcbh(bxBxsq.getLcbh());
                        step.setLcid(bxBxsq.getId());
                        step.setStep(1);
                        step.setSpr(userId);
                        JsonEntity<TSysWfStep> jsonEntity = new JsonEntity<>();
                        jsonEntity.setData(step);
                        String co=wfManagerDomain.saveOrUpdate(JsonUtils.toJson(jsonEntity));
                        if(StringUtils.isNotBlank(co)){
                            JsonEntity<TSysWfStep> jsonEntity1=JsonUtils.toCollection(co, new TypeReference<JsonEntity<TSysWfStep>>() {
                            });
                            if(null!=jsonEntity1){
                                step=jsonEntity1.getData();
                            }
                        }
                    }
                    if (StringUtils.isNotBlank(step.getSpr())) {
                        if (userId.equals(step.getSpr())) {//验证通过执行下一步
                            String date=DateFormatUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm");
                            step.setJssj(date);
                            JsonEntity<TSysWfStep> stepJsonEntity = new JsonEntity<>();
                            stepJsonEntity.setData(step);
                            //结束已有的待办
                            wfManagerDomain.saveOrUpdate(JsonUtils.toJson(stepJsonEntity));
                            //创建新的待办
                            TSysWfStep wfStep=new TSysWfStep();
                            wfStep.setKssj(bxBxsq.getBxsj());
                            wfStep.setLcbh(bxBxsq.getLcbh());
                            wfStep.setLcid(bxBxsq.getId());
                            wfStep.setStep(stepId+1);
                            stepJsonEntity.setData(wfStep);
                            wfManagerDomain.saveOrUpdate(JsonUtils.toJson(stepJsonEntity));
                            return true;
                        }
                    }
                }else if(stepId<=4){//非第一步，中间步骤
                    String code=informationDomain.getUserRoleOrgId(userId);//查询用户信息，包含角色集合，部门集合
                    TSysWfStep step = getDbStep(stepId, bxBxsq.getLcbh());
                    if(StringUtils.isNotBlank(code)){
                        JsonEntity<TUserInformation> jsonEntity=JsonUtils.toCollection(code,
                                new TypeReference<JsonEntity<TUserInformation>>() {
                        });
                        if(null!=jsonEntity){
                            TUserInformation userInformation=jsonEntity.getData();
                            //查询用户是否有权限
                            String code_if=stepInformationDomain.queryRoleStepOauth(userInformation.getId(),stepId,
                                    userInformation.getRoleIds(),userInformation.getOrgIds());
                            if(StringUtils.isNotBlank(code_if)){
                                JsonEntity<TMessage> messageJsonEntity=JsonUtils.toCollection(code_if, new TypeReference<JsonEntity<TMessage>>() {
                                });
                                if(null!=messageJsonEntity){
                                    TMessage message=messageJsonEntity.getData();
                                    if(message.getOauth()){//用户有权限
                                        String date=DateFormatUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm");
                                        step.setJssj(date);
                                        JsonEntity<TSysWfStep> stepJsonEntity = new JsonEntity<>();
                                        stepJsonEntity.setData(step);
                                        //结束已有的待办
                                        wfManagerDomain.saveOrUpdate(JsonUtils.toJson(stepJsonEntity));
                                        //创建新的待办
                                        TSysWfStep wfStep=new TSysWfStep();
                                        wfStep.setKssj(bxBxsq.getBxsj());
                                        wfStep.setLcbh(bxBxsq.getLcbh());
                                        wfStep.setLcid(bxBxsq.getId());
                                        wfStep.setStep(stepId+1);
                                        stepJsonEntity.setData(wfStep);
                                        wfManagerDomain.saveOrUpdate(JsonUtils.toJson(stepJsonEntity));
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }else {//最后一步
                    if(userId.equals(bxBxsq.getBxr())){//最后结束的人为发起人
                        TSysWfStep step = getDbStep(stepId, bxBxsq.getLcbh());
                        if(null!=step){
                            String date=DateFormatUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm");
                            step.setJssj(date);
                            JsonEntity<TSysWfStep> stepJsonEntity = new JsonEntity<>();
                            stepJsonEntity.setData(step);
                            //结束已有的待办
                            wfManagerDomain.saveOrUpdate(JsonUtils.toJson(stepJsonEntity));
                        }
                    }
                }
                //保存流程内容
                JsonEntity<TBxBxsq> jsonEntity = new JsonEntity<>();
                jsonEntity.setData(bxBxsq);
                bxsqManagerDomain.saveOrUpdate(JsonUtils.toJson(jsonEntity));
                return true;
            } catch (ParseException e) {
                log.error("日期格式化错误："+e.getLocalizedMessage());
            }
        }
        return false;
    }

    /**
     * 获取待办步骤
     *
     * @param stepId
     * @param str
     * @return
     */
    private TSysWfStep getDbStep(Integer stepId, String str) {
        TSysWfStep sysWfStep = null;
        String code_step = wfManagerDomain.queryStepEntity(stepId, str);
        if (StringUtils.isNotBlank(code_step)) {
            JsonEntity<TSysWfStep> stepJsonEntity = JsonUtils.toCollection(code_step, new TypeReference<JsonEntity<TSysWfStep>>() {
            });
            sysWfStep = stepJsonEntity.getData();
        }
        return sysWfStep;
    }


    /**
     * 区域信息
     *
     * @return
     */
    private List<TBxLyqy> getAllLyxx() {
        String code = lyqyManagerDomain.getAll();
        List<TBxLyqy> list = null;
        if (StringUtils.isNotBlank(code)) {
            JsonArray<TBxLyqy> jsonArray = JsonUtils.toCollection(code, new TypeReference<JsonArray<TBxLyqy>>() {
            });
            if (null != jsonArray) {
                list = jsonArray.getDataList();
            }
        }
        return list;
    }

    /**
     * 楼宇信息
     *
     * @param id
     * @return
     */
    private List<TBxLyxx> getAllLyxx(Integer id) {
        List<TBxLyxx> list = null;
        String code = lyxxManagerDomain.getAll(id);
        if (StringUtils.isNotBlank(code)) {
            JsonArray<TBxLyxx> jsonArray = JsonUtils.toCollection(code, new TypeReference<JsonArray<TBxLyxx>>() {
            });
            if (null != jsonArray) {
                list = jsonArray.getDataList();
            }
        }
        return list;
    }
}
